﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Quest.ConsoleApp
{
    public static class ReflectionExpansion
    {
        /// <summary>
        /// DataRow转实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T ToModel<T>(this DataRow dr) where T : new()
        {
            if (dr == null) return default(T);
            var list = dr.Table.ToList<T>();
            if (list == null || list.Count == 0) return default(T);
            return list[0];
        }

        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt) where T : new()
        {
            if (dt == null) return null;
            List<T> list = new List<T>();
            Type t = typeof(T);
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn column in dt.Columns)
                {
                    T model = new T();
                    foreach (PropertyInfo item in t.GetProperties())
                    {
                        if (item.Name.Equals(column.ColumnName, StringComparison.OrdinalIgnoreCase) ||
                            item.Name.Replace("_", "").Equals(column.ColumnName.Replace("_", ""), StringComparison.OrdinalIgnoreCase))
                        {
                            var obj = dr[column.ColumnName].SafeValue(item.PropertyType);
                            if (obj != null) item.SetValue(obj, model);
                        }
                    }
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 安全值转换
        /// </summary>
        /// <param name="value">转换前的值</param>
        /// <param name="t">转换后的类型</param>
        /// <returns>转换后的值（转换失败返回默认值）</returns>
        public static object SafeValue(this object value, Type t)
        {
            if (value == null) return t.IsValueType ? Activator.CreateInstance(t) : null;
            try
            {
                if (t.IsEnum)
                {
                    return Enum.Parse(t, value.ToString());
                }
                else if (t == typeof(Guid))
                {
                    return Guid.Parse(value.ToString());
                }
                return Convert.ChangeType(value, t);
            }
            catch (Exception e)
            {
                return t.IsValueType ? Activator.CreateInstance(t) : null;
            }
        }

        /// <summary>
        /// 安全值转换
        /// </summary>
        /// <typeparam name="T">转换后的类型</typeparam>
        /// <param name="obj">转换前的值</param>
        /// <returns>转换后的值（转换失败返回默认值）</returns>
        public static T SafeValue<T>(this object value)
        {
            Type type = typeof(T);
            object result = value.SafeValue(type);
            if (result == null) return default(T);
            return (T)result;
        }
    }
}
